//
//  FTBrowserAlbumController.m
//  Decathlon
//
//  Created on 14-2-11.
//  Copyright (c) 2014年. All rights reserved.
//

#import "FTBrowserAlbumController.h"
#import "FTAlbumPhotoControllerDelegate.h"
//#import "DcNBaseNavigationController.h"
#import "ASBaseNavigationController.h"
//#import "UIView+RCSToast.h"
//#import "RCSChatViewController.h"
//#import "RcSFileUtil.h"


#define PADDING 20
#define OriginalImageTag 100000
#define OriginBtnTag    200000
#define KFileSizeMaxLenght 500*1024*1024  //发送文件最大限制

//static const CGFloat kFooterViewHeight = 44.0f;
static const CGFloat kBtnPaddingLeft   = 15.0f;
//static const CGFloat kBtnLeftViewWidth = 95.0f;
//static const CGFloat kBtnPaddingTop    = 15.0f;
static const CGFloat kBtnWidth         = 75.0f;
//static const CGFloat kBtnHeight        = 30.0f;
static const CGFloat kSendBtnHeight    = 32.0f;
static const CGFloat kFootBarViewHeight = 50.5f;

@interface FTBrowserAlbumController ()
{
    NSInteger  _selectIndex;
    CGFloat    _lastOffset;
    UIImageView *_footerView;
    UILabel *_yuantuLable;
}

@property(nonatomic,assign) NSInteger selectIndex;
@property(nonatomic,assign) NSInteger photoCount;
@property(nonatomic,assign) NSInteger thumbnailTag;
@property(nonatomic,strong) NSMutableArray *photoViewsArray;
@property(nonatomic,strong) NSMutableDictionary *selectPhotosDict;//所有已选择图片
@property(nonatomic,strong) NSMutableArray *selectKeys;
@property(nonatomic,strong) UIButton *originBtn;
@property(nonatomic,strong) UIButton *sendBtn;

@end

@implementation FTBrowserAlbumController
@synthesize assetsArray = _assetsArray;
@synthesize selectIndex = _selectIndex;
@synthesize albumScrollView = _albumScrollView;
@synthesize photoCount = _photoCount;
@synthesize photoViewsArray = _photoViewsArray;
@synthesize thumbnailTag = _thumbnailTag;
@synthesize selectPhotosDict = _selectPhotosDict;
@synthesize selectKeys = _selectKeys;
@synthesize originBtn = _originBtn;
@synthesize albumDelegate = _albumDelegate;
@synthesize delegate = _delegate;
@synthesize sendBtn = _sendBtn;
@synthesize albumType = _albumType;
@synthesize isSendOrigin = _isSendOrigin;

- (void)dealloc
{
    self.albumScrollView = nil;
    self.selectPhotosDict = nil;
    self.selectKeys = nil;
    self.assetsArray = nil;
    _footerView = nil;
}

/**
 *  只预览选中的图片时，重新定义key/value
 */
-(void)initSelectPhotoDict
{
    _selectPhotosDict = [[NSMutableDictionary alloc] init];
    NSUInteger count = self.assetsArray.count;
    
    for (int i = 0; i < count; i ++)
    {
        ALAsset *aset = (ALAsset *)[self.assetsArray objectAtIndex:i];
        NSString *key = [NSString stringWithFormat:@"%d",i];
        [_selectPhotosDict setObject:aset forKey:key];
    }
    _selectKeys = [[NSMutableArray alloc] initWithArray:[_selectPhotosDict allKeys]];
}


- (id)initWithSelectIndex:(NSInteger)index
            andAssetsDict:(NSMutableDictionary *)dic
            andSelectKeys:(NSMutableArray *)selectKeys
             andAllAssets:(NSMutableArray *)assetsArr
             isPartBrower:(BOOL)isPart
            andSendOrigin:(BOOL)isOrigin
{
    if (self = [super init])
    {
        self.selectIndex = index;
        
        _isSendOrigin = isOrigin;
        
        _assetsArray = [[NSMutableArray alloc] initWithArray:assetsArr];
        
        if (isPart)
        {
            [self initSelectPhotoDict];
        }
        else
        {
            _selectKeys = [[NSMutableArray alloc] initWithArray:selectKeys];
            
            _selectPhotosDict = [[NSMutableDictionary alloc] initWithDictionary:dic];
        }
        
        self.photoCount = [self.assetsArray count];
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	
	if (SYSTEM_VERSION < 7.0)
	{
		self.wantsFullScreenLayout = NO;
		self.navigationController.navigationBar.translucent = NO;
	}
	else
	{
		self.automaticallyAdjustsScrollViewInsets = YES;
		self.edgesForExtendedLayout = UIRectEdgeAll;
		self.extendedLayoutIncludesOpaqueBars = NO;
	}
	
	_bHiddenNav = NO;
	[UIApplication sharedApplication].statusBarHidden = NO;
	[self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    //[self setStrNavTitle:@"预览"];
    
	//设置navigationBar，隐藏时不会改变视图大小
	if (SYSTEM_VERSION < 7.0)
	{
		self.wantsFullScreenLayout = YES;
		self.navigationController.navigationBar.translucent = YES;
	}
	else
	{
		self.automaticallyAdjustsScrollViewInsets = NO;
		self.edgesForExtendedLayout = UIRectEdgeAll;
		self.extendedLayoutIncludesOpaqueBars = YES;
	}
	
    CGRect scrollFrame = [self frameForPagingScrollView];
     _albumScrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];
    _albumScrollView.userInteractionEnabled = YES;
    [_albumScrollView setDelegate:self];
    [_albumScrollView setBackgroundColor:[UIColor clearColor]];
    [_albumScrollView setPagingEnabled:YES];
    [_albumScrollView setShowsVerticalScrollIndicator:NO];
    [_albumScrollView setShowsHorizontalScrollIndicator:NO];
    [self.view addSubview:_albumScrollView];
    
    if (self.albumType == AlbumType_SingleForPhoto)
    {
        //[self setRightText:@"使用"];
    }
    else
    {
        [self judgeCurrentPicSelected];
        [self initFooterView];
    }
	
    [self setScrollViewContentSize];
    
    _photoViewsArray = [[NSMutableArray alloc] initWithCapacity:self.photoCount];
    for (int i=0; i < self.photoCount; i++)
    {
        [_photoViewsArray addObject:[NSNull null]];
    }
    
    [self setCurrentIndex:_selectIndex];
    
    [self scrollToIndex:_selectIndex];
    
    [self loadOriginalImg:_selectIndex];
}


/**
 *  绘制底部工具栏
 */
- (void)initFooterView
{
    CGRect rect = [UIScreen mainScreen].bounds;

	_footerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, rect.size.height - kFootBarViewHeight, rect.size.width, kFootBarViewHeight)];
    _footerView.userInteractionEnabled = YES;
	_footerView.image = [[UIImage imageNamed:@"message_bottom_bg"] stretchableImageWithLeftCapWidth:0 topCapHeight:1];
    [self.view addSubview:_footerView];
    
//  if (self.albumType == AlbumType_SingleForSending)
    {
          //mod by doufj 20150812 不让原图按钮显示
//        UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kBtnLeftViewWidth, kFooterViewHeight)];
//        leftButton.backgroundColor = [UIColor clearColor];
//        
//        _originBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        _originBtn.tag = OriginBtnTag;
//        _originBtn.userInteractionEnabled = NO;
//        _originBtn.backgroundColor = [UIColor clearColor];
//        _originBtn.frame = CGRectMake(kBtnPaddingLeft, (kFootBarViewHeight - 20)/2, 20, 20);
//        _originBtn.selected = _isSendOrigin;
//        if (!_isSendOrigin)
//        {
//            [self.originBtn setBackgroundImage:[UIImage imageNamed:@"common_unselect"] forState:UIControlStateNormal];//取消
//        }
//        else
//        {
//            [self.originBtn setBackgroundImage:[UIImage imageNamed:@"common_originselect"] forState:UIControlStateNormal];//选择
//        }
//        [leftButton addSubview:_originBtn];
//        
//        _yuantuLable = [[UILabel alloc] initWithFrame:CGRectMake(kBtnPaddingLeft + _originBtn.frame.size.width + 5,
//                                                                 (kFootBarViewHeight - kBtnHeight)/2,
//                                                                 200,
//                                                                 kBtnHeight)];
//        _yuantuLable.text = @"原图";
//        _yuantuLable.backgroundColor = [UIColor clearColor];
//        _yuantuLable.textColor = RGB(134, 139, 142);
//        _yuantuLable.font = [UIFont systemFontOfSize:12];
//        _yuantuLable.textAlignment = NSTextAlignmentLeft;
//        [leftButton addSubview:_yuantuLable];
//        
//        [leftButton addTarget:self action:@selector(selectOriginalPic:) forControlEvents:UIControlEventTouchUpInside];
//        [_footerView addSubview:leftButton];
    }
    
    _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sendBtn.frame = CGRectMake(rect.size.width - kBtnPaddingLeft - kBtnWidth, (kFootBarViewHeight - kSendBtnHeight)/2, kBtnWidth, kSendBtnHeight);
    _sendBtn.showsTouchWhenHighlighted = NO;
    [_sendBtn setBackgroundImage:[[UIImage imageNamed:@"message_btn_green_normal"] stretchableImageWithLeftCapWidth:6 topCapHeight:6] forState:UIControlStateNormal];
    [_sendBtn setBackgroundImage:[[UIImage imageNamed:@"message_btn_green_pressed"] stretchableImageWithLeftCapWidth:6 topCapHeight:6] forState:UIControlStateHighlighted];
    [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [_sendBtn.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [_sendBtn addTarget:self action:@selector(sendBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_footerView addSubview:_sendBtn];
	
	//added 0407增加进入该视图判断“发送”按钮状态
	if (_selectKeys.count <= 0)
	{
	    [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
		_sendBtn.enabled = NO;
	}
	else
	{
	    [_sendBtn setTitle:[NSString stringWithFormat:@"%@(%lu/9)", (@"发送"), (unsigned long)_selectKeys.count] forState:UIControlStateNormal];
		_sendBtn.enabled = YES;
	}
    
    if(AlbumType_SingleForSendingForFile == _albumType)
    {
        [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        _sendBtn.enabled = YES;
    }
    [self judgeIsSendOrigion];
}

/**
 *  设置ScrollView内容大小
 */
- (void)setScrollViewContentSize
{
    NSInteger pageCount = self.photoCount;
    if (pageCount == 0)
    {
        pageCount = 1;
    }

	CGSize size = CGSizeMake(_albumScrollView.frame.size.width * pageCount,
							 _albumScrollView.frame.size.height);
    [_albumScrollView setContentSize:size];
}


/**
 *  设置当前页照片视图并销毁前后视图
 *
 *  @param newIndex 当前照片索引
 */
- (void)setCurrentIndex:(NSInteger)newIndex
{
    _selectIndex = newIndex;
    
    if (_selectIndex < 0 || _selectIndex >= self.photoCount)
    {
        return;
    }
    
    [self loadPhoto:_selectIndex];
    [self loadPhoto:_selectIndex + 1];
    [self loadPhoto:_selectIndex - 1];
    [self unloadPhoto:_selectIndex + 2];
    [self unloadPhoto:_selectIndex - 2];
}

/**
 *  滑动到当前索引照片
 *
 *  @param index 照片索引
 */
- (void)scrollToIndex:(NSInteger)index
{
    CGRect frame = _albumScrollView.frame;
    
    frame.origin.x = frame.size.width * index;
    frame.origin.y = 0;
    
    [_albumScrollView scrollRectToVisible:frame animated:NO];
}

/**
 *  设置scrollViewFrame
 *
 */
- (CGRect)frameForPagingScrollView
{
    CGRect frame;
    CGRect screenFrame = [[UIScreen mainScreen] bounds];
    
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation))
    {
        screenFrame.origin.x -= PADDING;
        screenFrame.size.height += (2 * PADDING);
        frame = CGRectMake(screenFrame.origin.x, 0, screenFrame.size.height, screenFrame.size.width);
    }
    else
    {
        screenFrame.origin.x -= PADDING;
        screenFrame.size.width += (2 * PADDING);
        
        if (self.albumType == AlbumType_SingleForPhoto)
        {
            frame = CGRectMake(screenFrame.origin.x, 0, screenFrame.size.width, screenFrame.size.height);
        }
        else
        {
			//frame = CGRectMake(screenFrame.origin.x, 0, screenFrame.size.width, screenFrame.size.height - kFooterViewHeight);
		    frame = CGRectMake(screenFrame.origin.x, 0, screenFrame.size.width, screenFrame.size.height);
        }
    }
    
    return frame;
}


/**
 *  获取当前页frame
 *
 *  @param index 索引
 *
 */
- (CGRect)frameForPageAtIndex:(NSUInteger)index
{
    CGRect bounds = [_albumScrollView bounds];
    CGRect pageFrame = bounds;
    pageFrame.size.width -= (2 * PADDING);
    pageFrame.origin.x = (bounds.size.width * index) + PADDING;

    return pageFrame;
}

/**
 *  加载显示全屏高清图
 *
 *  @param index 索引
 */
- (void)loadOriginalImg:(NSInteger)index
{
    __weak typeof(self) weakSelf = self;
    
    dispatch_queue_t lookQueue = dispatch_queue_create("Fetion:lookQueue", NULL);
    
    dispatch_async(lookQueue, ^(void){
        
        ALAsset *ldAsset = [weakSelf.assetsArray objectAtIndex:index];
        
        if (![[ldAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
        {
            dispatch_async(dispatch_get_main_queue(), ^(void){
                
                UIImage *originalImg = [UIImage imageWithCGImage:ldAsset.defaultRepresentation.fullScreenImage];
                
                for (int i = 0; i < [_albumScrollView.subviews count]; i++)
                {
                    FTImageScrollView *ldView = [_albumScrollView.subviews objectAtIndex:i];
                    if (ldView.tag == _selectIndex)
                    {
                        _thumbnailTag = ldView.tag;
                        ldView.tag = OriginalImageTag;
                        [ldView loadImage:originalImg];
                    }
                }
                
            });
        }
        
    });
    
    //dispatch_release(lookQueue);
}

/**
 *  加载显示缩略图
 *
 *  @param index 索引
 */
- (void)loadPhoto:(NSInteger)index
{
    if (index < 0 || index >= self.photoCount)
    {
        return;
    }
    
    id currentPhotoView = [_photoViewsArray objectAtIndex:index];
    if (NO == [currentPhotoView isKindOfClass:[FTImageScrollView class]])
    {
        CGRect frame = [self frameForPageAtIndex:index];
        FTImageScrollView *_imgScrollView = [[FTImageScrollView alloc] initWithFrame:frame];
        _imgScrollView.imgSclDelegate = self;
        
        ALAsset *ldAsset = [self.assetsArray objectAtIndex:index];
        
        dispatch_queue_t lookQueue = dispatch_queue_create("Fetion:lookImage", NULL);
        
        dispatch_async(lookQueue, ^(void){
            
            UIImage *lookImage = [UIImage imageWithCGImage:ldAsset.aspectRatioThumbnail];
            
            dispatch_async(dispatch_get_main_queue(), ^(void){
                
                [_imgScrollView loadImage:lookImage];
                
            });
            
        });
        
        //dispatch_release(lookQueue);
        
        _imgScrollView.tag = index;
        _imgScrollView.userInteractionEnabled = YES;
        
        [_albumScrollView addSubview:_imgScrollView];
        [_photoViewsArray replaceObjectAtIndex:index withObject:_imgScrollView];
    }
}

/**
 *  移除图片
 *
 *  @param index 索引
 */
- (void)unloadPhoto:(NSInteger)index
{
    if (index < 0 || index >= self.photoCount)
    {
        return;
    }
    
    id currentPhotoView = [_photoViewsArray objectAtIndex:index];
    if ([currentPhotoView isKindOfClass:[FTImageScrollView class]])
    {
        [currentPhotoView removeFromSuperview];
        [_photoViewsArray replaceObjectAtIndex:index withObject:[NSNull null]];
    }
}

//隐藏导航栏
-(void)hiddenNavView:(BOOL)hidden animated:(BOOL)bAnimated
{
	if (_bHiddenNav == hidden)
	{
		return;
	}
	
	_bHiddenNav = hidden;
    
    _footerView.hidden = _bHiddenNav;
	
	//隐藏状态栏
	if (SYSTEM_VERSION < 7.0)
	{
		[UIApplication sharedApplication].statusBarHidden = _bHiddenNav;
	}
	else
	{
		[self setNeedsStatusBarAppearanceUpdate];
		[UIApplication sharedApplication].statusBarHidden = _bHiddenNav;
	}
	
	[self.navigationController setNavigationBarHidden:_bHiddenNav animated:bAnimated];
}

#pragma mark - FTImageScrollDelegate

-(void)singleTap:(FTImageScrollView*)scrollView
{
    [self hiddenNavView:!_bHiddenNav animated:YES];
}

-(void)doubleTap:(FTImageScrollView*)scrollView
{
    if (scrollView.zoomScale == 1.0)
    {
        [scrollView setZoomScale:2.0 animated:YES];
    }
    else
    {
        [scrollView setZoomScale:1.0 animated:YES];
    }
}

#pragma mark - UIScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    CGFloat curOffset = scrollView.contentOffset.x;
    float fractionalPage = curOffset / pageWidth;
    NSInteger page = floor(fractionalPage);
	if (page != _selectIndex && fabs(curOffset - _lastOffset) > 200.0)
    {
		[self setCurrentIndex:page];
        
         if ((self.albumType != AlbumType_SingleForPhoto) && (_selectIndex >= 0))
         {
             ALAsset *asset = [self.assetsArray objectAtIndex:_selectIndex];
             if ([self.selectPhotosDict.allValues containsObject:asset])
             {
                [self setRightButtonWithImageName:@"message_album_select" bgImageName:nil];
             }
             else
             {
                 [self setRightButtonWithImageName:@"common_unselect" bgImageName:nil];
             }
         }
	}
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    for (int i = 0; i < [_albumScrollView.subviews count]; i++)
    {
        FTImageScrollView *ldView = [_albumScrollView.subviews objectAtIndex:i];
        
        if (ldView.tag == OriginalImageTag)
        {
            ALAsset *ldAsset = [self.assetsArray objectAtIndex:_thumbnailTag];
            
            ldView.tag = _thumbnailTag;
            
            dispatch_queue_t replacePreQueue = dispatch_queue_create("ReplaceThumbnail", NULL);
            
            dispatch_async(replacePreQueue, ^(void){
                
                UIImage *lookImage = [UIImage imageWithCGImage:ldAsset.aspectRatioThumbnail];
    
                dispatch_async(dispatch_get_main_queue(), ^(void){
                    
                    [ldView loadImage:lookImage];
                });
            });
            //dispatch_release(replacePreQueue);
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (_selectIndex >= 0)
    {
        _lastOffset = scrollView.contentOffset.x;
    }
    
    if (self.albumType != AlbumType_SingleForPhoto)
    {
        [self judgeCurrentPicSelected];
    }
    
    for (int i = 0; i < [_albumScrollView.subviews count]; i++)
    {
        FTImageScrollView *ldView = [_albumScrollView.subviews objectAtIndex:i];
        
        if (ldView.tag == _selectIndex)
        {
            ALAsset *ldAsset = [self.assetsArray objectAtIndex:ldView.tag];
            
            _thumbnailTag = ldView.tag;
            ldView.tag = OriginalImageTag;
            
            if (![[ldAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
            {
                dispatch_queue_t lookQueue = dispatch_queue_create("Fetion:lookImage", NULL);
                
                dispatch_async(lookQueue, ^(void){
                
                    dispatch_async(dispatch_get_main_queue(), ^(void){
                        
                        UIImage *originalImg = [UIImage imageWithCGImage:ldAsset.defaultRepresentation.fullScreenImage];
                        [ldView loadImage:originalImg];
                    });
                    
                });
                
                //dispatch_release(lookQueue);
            }
        }
    }
}

/**
 *  判断当前照片选择情况
 */
- (void)judgeCurrentPicSelected
{
    ALAsset *asset = [self.assetsArray objectAtIndex:_selectIndex];
    
    if ([self.selectPhotosDict.allValues containsObject:asset])
    {
         [self setRightButtonWithImageName:@"message_album_select" bgImageName:nil];
    }
    else
    {
        [self setRightButtonWithImageName:@"common_unselect" bgImageName:nil];
    }

    [self judgeIsSendOrigion];
}

-(void)judgeIsSendOrigion{
    
    if (_isSendOrigin)
    {
        long long fileSize = [[[self.assetsArray objectAtIndex:_selectIndex] defaultRepresentation] size];
        fileSize = fileSize/1024;//K
        NSString *unit = @"K";
        if (fileSize >= 1024)
        {
            CGFloat fsize = (fileSize * 0.1)/(1024 * 0.1);
            unit = @"M";
            _yuantuLable.text = [NSString stringWithFormat:@"原图(%.1f%@)",fsize,unit];
        }
        else
        {
            _yuantuLable.text = [NSString stringWithFormat:@"原图(%lld%@)",fileSize,unit];
        }
        
    }
    else
    {
        _yuantuLable.text = [NSString stringWithFormat:@"原图"];
    }
}

/**
 *  点击发送按钮
 *
 *  @param sender 发送按钮
 */
- (void)sendBtnPressed:(id)sender
{
    __weak typeof(self) weakSelf = self;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if(weakSelf.albumDelegate && [weakSelf.albumDelegate respondsToSelector:@selector(albumDidFinishPickingWithInfo:IsOriginImg: withAlbumType:)])
        {
            //不选择直接发送当前页图片
            if (weakSelf.selectPhotosDict.count == 0)
            {
                [weakSelf rightButtonPressed:nil];
                
                [weakSelf sendBtnPressed:nil];
                
                return;
            }
            
            NSMutableArray *selectPhotosArr = [[NSMutableArray alloc] init];
            
            for (int i = 0; i < weakSelf.selectKeys.count; i++)
            {
                NSString *key = [weakSelf.selectKeys objectAtIndex:i];
                ALAsset *tempALAset = (ALAsset *)[weakSelf.selectPhotosDict objectForKey:key];
                
                if (_isSendOrigin)//_originBtn.selected
                {
                    @autoreleasepool
                    {
                        NSUInteger size = (NSUInteger)[tempALAset.defaultRepresentation size];
                        uint8_t *buff = (uint8_t*)malloc(size);
                        NSError *err = nil;
                        [tempALAset.defaultRepresentation getBytes:buff fromOffset:0 length:size error:&err];
                        if (err)
                        {
                            //ErrorLog("发送原图：%s",err.localizedFailureReason.UTF8String);
                        }
                        //不需要再调用free()
                        NSData *originScreenImgData = [NSData dataWithBytesNoCopy:buff length:size freeWhenDone:YES];
                        
                        if (originScreenImgData)
                        {
                            [selectPhotosArr addObject:originScreenImgData];
                        }
                    }
                }
                else
                {
                    NSData *fullScreenImgData = UIImageJPEGRepresentation([UIImage imageWithCGImage:tempALAset.defaultRepresentation.fullScreenImage], 1);;
                    if (fullScreenImgData)
                    {
                        [selectPhotosArr addObject:fullScreenImgData];
                    }
                }
            }
            
            if (_isSendOrigin)//_originBtn.selected
            {
                if (AlbumType_SingleForSendingForFile == self.albumType) {
                    if (((NSData *)[selectPhotosArr objectAtIndex:0]).length > KFileSizeMaxLenght) {
                        [weakSelf showTipWithMessage:@"发送文件大小应小于500M"];
                        return;
                    }
                }
                [weakSelf.albumDelegate albumDidFinishPickingWithInfo:selectPhotosArr IsOriginImg:YES withAlbumType:self.albumType];
            }
            else
            {
                [weakSelf.albumDelegate albumDidFinishPickingWithInfo:selectPhotosArr IsOriginImg:NO withAlbumType:self.albumType];
            }
        }
        
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
        
        if (self.isComeFromWiFi)
        {
            //[[NSNotificationCenter defaultCenter] postNotificationName:MSG_FileTransferWhenCallNotification object:nil];
        }

    });
}

/**
 *选择文件大小不超过500M
 */
-(void)showTipWithMessage:(NSString *)tipMessage
{
    //[self.view rcsmakeToast:tipMessage duration:2.0 position:@"center"];
}

//原图勾选
- (void)selectOriginalPic:(id)sender
{
    UIButton *selectButton  = (UIButton *)[self.view viewWithTag:OriginBtnTag];
    if (selectButton.selected)
    {
        //取消
        [self.originBtn setBackgroundImage:[UIImage imageNamed:@"common_unselect"] forState:UIControlStateNormal];
     }
    else
    {
        //选择
        //[self.originBtn setBackgroundImage:[RCSFontManage imageNamed:@"common_select"] forState:UIControlStateNormal];
        [self.originBtn setBackgroundImage:[UIImage imageNamed:@"common_originselect"] forState:UIControlStateNormal];
    }
    selectButton.selected = !selectButton.selected;
    _isSendOrigin = selectButton.selected;

    [self judgeIsSendOrigion];
}


//取消
- (void)leftButtonPressed:(id)sender
{
    _albumScrollView.delegate = nil;//置为nil，否则会调用pop会调用delegate方法
    
    //多图，先将上一个界面刷新
    if (self.albumType == AlbumType_MutiForSending)
    {
        [self reloadLastData];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)reloadLastData
{
    if (self.delegate && [self.delegate conformsToProtocol:@protocol(FTBrowserAlbumControllerDelegate)])
    {
        [self.delegate compareWithDict:self.selectPhotosDict];
    }
}


//选择、使用照片
- (void)rightButtonPressed:(id)sender
{
    if (self.albumType == AlbumType_SingleForPhoto)
    {
        NSMutableArray *selectPhotosArr = [[NSMutableArray alloc] init];
       
        if ([self.assetsArray count] > 0)
        {
            ALAsset *ldAsset = [self.assetsArray objectAtIndex:_selectIndex];
            UIImage *fullImg = [UIImage imageWithCGImage:ldAsset.defaultRepresentation.fullScreenImage];
            if (fullImg)
            {
                [selectPhotosArr addObject:fullImg];
            }
        }
        
        [self.albumDelegate albumDidFinishPickingWithInfo:selectPhotosArr IsOriginImg:NO withAlbumType:self.albumType];
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    else
    {
        NSString *currentIndex = [NSString stringWithFormat:@"%ld",(long)_selectIndex];
        if ([self.selectPhotosDict objectForKey:currentIndex])
        {
            //取消
			//[self setRightButtonWithImageName:nil bgImageName:nil];
		    [self setRightButtonWithImageName:@"common_unselect" bgImageName:nil];
            [self.selectPhotosDict removeObjectForKey:currentIndex];
            [self.selectKeys removeObject:currentIndex];
        }
        else
        {
            //选择
            if (self.selectKeys.count >= 9)
            {
                //此处弹出最多只可发送9张的提示语
                //[self.view rcsmakeToast:@"最多只可发送9张"];
                return;
            }
            
            [self setRightButtonWithImageName:@"message_album_select" bgImageName:nil];
            ALAsset *asset = [self.assetsArray objectAtIndex:[currentIndex intValue]];
            [self.selectPhotosDict setObject:asset forKey:currentIndex];
            [self.selectKeys addObject:currentIndex];
        }
        
//      [_sendBtn setTitle:[NSString stringWithFormat:@"%@(%d/%d)",(@"发送"),_selectIndex+1,[self.assetsArray count]] forState:UIControlStateNormal];
        if (self.selectKeys.count <= 0)
		{
		    [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
            _sendBtn.enabled = NO;
        }
		else
		{
            if(AlbumType_SingleForSendingForFile == _albumType)
            {
                [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
            }
            else
            {
                [_sendBtn setTitle:[NSString stringWithFormat:@"%@(%d/9)", (@"发送"), self.selectKeys.count] forState:UIControlStateNormal];
            }

            _sendBtn.enabled = YES;
        }
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(BOOL)canDragBack
{
    if (self.selectIndex == 0)
    {
        [self reloadLastData];
        return YES;
    }
    return NO;
}

@end
